package com.xiaoshi.oauth;

import com.xiaoshi.common.MyResUser;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;


import java.util.Map;

/**
 * 自定义抽象令牌授予者
 */
public abstract class AbstractCustomTokenGranter extends AbstractTokenGranter {

    private final OAuth2RequestFactory requestFactory;


    protected AbstractCustomTokenGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, String grantType) {
        super(tokenServices, clientDetailsService, requestFactory, grantType);
        this.requestFactory = requestFactory;
    }

    @Override
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
        Map<String, String> parameters = tokenRequest.getRequestParameters();
        MyResUser myResUser = userLogin(parameters);


        OAuth2Request storedOAuth2Request = requestFactory.createOAuth2Request(client, tokenRequest);

        //PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken(myResUser, null, myResUser.getAuthorities());

        PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken(myResUser, parameters, myResUser.getAuthorities());
        authentication.setDetails(myResUser);
        OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(storedOAuth2Request, authentication);
        return oAuth2Authentication;
    }


    /**
     * 登入
     *
     * @param parameters
     * @return
     */
    protected abstract MyResUser userLogin(Map<String, String> parameters);
}
